package com.example.travel.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.travel.domain.entity.Menu;
import com.example.travel.domain.entity.Role;
import com.example.travel.domain.entity.RoleMenu;
import com.example.travel.mapper.RoleMenuMapper;
import com.example.travel.mapper.RolesMapper;
import com.example.travel.service.MenuService;
import com.example.travel.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author : LinQingLiang
 * @file : RoleServiceImpl.java
 * @Since : 2023/1/30 21:24
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RolesMapper, Role> implements RoleService {

    @Autowired
    private RolesMapper rolesMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private MenuService menuService;

    @Override
    public Page page(Role role, Integer pageNum, Integer pageSize) {
        Page page = new Page(pageNum,pageSize);

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like(role.getName() != null && role.getName() != "","name",role.getName());
        wrapper.like(role.getDescription() != null && role.getDescription() != "","description",role.getDescription());
        return rolesMapper.page(page,wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void roleBindMenu(Integer roleId, List<Integer> menuIds) {

        roleMenuMapper.deleteByRoleId(roleId);

        List<Integer> menuIdsCopy = CollUtil.newArrayList(menuIds);
        //把前端传过来的菜单id数组绑定到当前的这个角色id上去
        for (Integer menuId:menuIds) {
            Menu menu = menuService.getById(menuId);
            if (menu.getPid() != null && !menuIdsCopy.contains(menu.getPid())){
                //二级菜单 并且传过来的menuId数组里面没有父级的id
                //补上这个父级id
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menu.getPid());
                roleMenuMapper.insert(roleMenu);
                menuIdsCopy.add(menu.getPid());
            }

            //再把前端传过来的菜单id数组绑定到当前的角色id上
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuMapper.insert(roleMenu);
        }
    }

    @Override
    public List<Integer> selectByRoleId(Integer roleId) {
        return roleMenuMapper.selectByRoleId(roleId);
    }

    @Override
    public Integer selectByFlag(String flag) {
        return rolesMapper.selectByFlag(flag);
    }
}
